package org.lee.streams;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jackielee
 * @version 1.0
 * @description streams
 * @date 2021/4/16
 */
public class Demo {

  public static void main(String[] args) {

    List<Apple> appleList = new ArrayList<>();
    appleList.add(new Apple(1, "苹果1", new BigDecimal("3.52"), 10));
    appleList.add(new Apple(2, "香蕉1", new BigDecimal("5.21"), 8));
    appleList.add(new Apple(3, "荔枝1", new BigDecimal("3.81"), 92));
    appleList.add(new Apple(3, "荔枝2", new BigDecimal("4.92"), 45));
    appleList.add(new Apple(2, "香蕉2", new BigDecimal("8.15"), 32));
    appleList.add(new Apple(1, "苹果6", new BigDecimal("3.98"), 5));

    Map<Integer, List<Apple>> groupby =
        appleList.stream().collect(Collectors.groupingBy(Apple::getId));
    System.out.println("groupby-id:" + groupby);

    Map<Integer, Apple> maps =
        appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a, (k1, k2) -> k1));
    System.out.println("maps:" + maps);

    Map<Integer, Apple> maps2 =
        appleList.stream()
            .collect(
                Collectors.toMap(
                    Apple::getId,
                    a -> a,
                    (k1, k2) ->
                        new Apple(
                            k1.getId(),
                            k1.getName() + ':' + k2.getName(),
                            k1.getMoney().add(k2.getMoney()),
                            k1.getNum() + k2.getNum())));
    System.out.println("maps2:" + maps2);

    List<Apple> apples =
        appleList.stream().filter(a -> a.getName().equals("苹果1")).collect(Collectors.toList());
    System.out.println("filters:" + apples);

    BigDecimal total =
        appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
    System.out.println("total money:" + total);

    Optional<Apple> appMax =
        appleList.stream().collect(Collectors.maxBy(Comparator.comparing(Apple::getMoney)));
    Optional<Apple> appMin =
        appleList.stream().collect(Collectors.minBy(Comparator.comparing(Apple::getMoney)));
    System.out.println("the max money and the min money:");
    appMax.ifPresent(System.out::println);
    appMin.ifPresent(System.out::println);
  }
}
